﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autofac;
using CommonSense.UI.Shell.Services;
using CommonSense.UI.Shell.Interfaces;

namespace CommonSense.UI.Startup.Services
{
    class DIContainer : IDIContainer
    {
        private IContainer container;
        private ContainerBuilder containerBuilder;

        public DIContainer()
        {
            this.containerBuilder = new ContainerBuilder();
        }

        public void RegisterSingletonInstance<T>(T instance) where T : class
        {
            if (this.container != null)
            {
                throw new InvalidOperationException("Cannot register instance in container that has been already configured");
            }
          
            this.containerBuilder.RegisterInstance<T>(instance);
        }

        public void RegisterSingletonType<TInterface, TImplementation>() where TImplementation : class
        {
            if (this.container != null)
            {
                throw new InvalidOperationException("Cannot register type in container that has been already configured");
            }
            
            this.containerBuilder.RegisterType<TImplementation>().As<TInterface>().SingleInstance();
        }

        public void Configure()
        {
            this.container = this.containerBuilder.Build();
        }

        public object Resolve(Type type)
        {
            if (this.container == null)
            {
                throw new InvalidOperationException("Cannot resolve type from di container because it's no configured yet");
            }
            return this.container.Resolve(type);
        }

        public TInterface Resolve<TInterface>()
        {
            return (TInterface)this.Resolve(typeof(TInterface));
        }
    }
}
